package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.GoodInfo;
import com.itheima.pojo.Result;
import com.itheima.service.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public Result search(Integer pageNum, Integer pageSize, String keyword) {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("name", keyword)).from(pageSize*(pageNum-1)).size(pageSize)
                .highlighter(new HighlightBuilder().field("name").preTags("<span style=\"color: red\">").postTags("</span>"));


        SearchRequest searchRequest = new SearchRequest("goods");
        searchRequest.source(builder);

        SearchResponse response = null;
        try {
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        SearchHits searchHits = response.getHits();
        System.out.println("共查到" + searchHits.getTotalHits().value + "条");

        SearchHit[] hits = searchHits.getHits();
        List<GoodInfo> list = new ArrayList<>();
        for (SearchHit hit : hits) {

            System.out.println("score:" + hit.getScore());
            GoodInfo goodInfo = JSON.parseObject(hit.getSourceAsString(), GoodInfo.class);
            if (hit.getHighlightFields() != null && hit.getHighlightFields().size() != 0)
                goodInfo.setName(StringUtils.join(hit.getHighlightFields().get("name").getFragments()));
            list.add(goodInfo);
            System.out.println(goodInfo);

        }
        long total = searchHits.getTotalHits().value;
        Result result = new Result();
        result.setData(list);
        result.setTotal((int)total);
        result.setPages((int)(total%pageSize==0?total/pageSize:total/pageSize+1));
        return result;
    }
}